﻿using System;
using System.Diagnostics;
using System.IO;
using NAnt.Core.Attributes;
using dotless.Core;
using dotless.Core.configuration;

namespace ECM7.NantContrib.Tasks.Compressor
{
	[TaskName("compile-less")]
	public class CompileLessTask : BaseTask
	{
		[TaskAttribute("file", Required = true)]
		public FileInfo File { get; set; }

		[TaskAttribute("result", Required = false)]
		public FileInfo Result { get; set; }

		protected override void ExecuteTask()
		{
			DateTime now = DateTime.Now;

			LogMessage("Starting compression...");

			string appPath = Directory.GetCurrentDirectory();
			string targetPath = File.DirectoryName ?? appPath;

			try
			{
				Directory.SetCurrentDirectory(targetPath);

				string defaultResultFileName = Path.GetFileNameWithoutExtension(File.Name) + ".css";
				string resultPath = Path.Combine(targetPath, defaultResultFileName);

				if (Result != null)
				{
					resultPath = Result.FullName;
				}
				
				var engine = CreateLessEngine(true);


				var source = System.IO.File.ReadAllText(File.FullName);
				var result = engine.TransformToCss(source, resultPath);

				System.IO.File.WriteAllText(resultPath, result);

			}
			finally
			{
				Directory.SetCurrentDirectory(appPath);
			}

			LogMessage("Finished compression.");
			LogMessage("Total time to execute task: {0}", DateTime.Now - now);
		}

		private ILessEngine CreateLessEngine(bool enableNativeMinification)
		{
			var config = DotlessConfiguration.GetDefault();
			config.MinifyOutput = enableNativeMinification;

			return new EngineFactory(config).GetEngine();
		}
	}
}
